package com.ruoyi.wx.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeEntity;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.PermissionService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysLoginService;
import com.ruoyi.wx.entity.dto.*;
import com.ruoyi.wx.entity.vo.WxUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 莫修
 * @date 2022/3/3
 */
@RestController
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Api(value = "微信用户接口", tags = {"微信用户接口测试"})
@RequestMapping("/wx")
public class WxUserLogin extends BaseController {


    private final SysLoginService sysLoginService;

    private final ISysDeptService sysDeptService;

    private final ISysUserService userService;

    private final PermissionService permissionService;

    @ApiOperation("微信登录接口")
    @GetMapping("/login")
    public AjaxResult wxLogin(String code) {
        if (code == null) {
            return AjaxResult.error("code不能为空");
        }
        String token = sysLoginService.wxLogin(code);
        return AjaxResult.success(token);
    }

    @ApiOperation("获取所有班级树图")
    @GetMapping("/getAllClass")
    public AjaxResult<List<GradeDTO>> getAllClass() {

        List<SysDept> list = sysDeptService.list(Wrappers.lambdaQuery(SysDept.class)
            .ne(SysDept::getAncestors, "0")
        );

        return AjaxResult.success(getClassTree(list));
    }


    public static List<GradeDTO> getClassTree(List<SysDept> list) {
        if (list == null) {
            return null;
        }
        Map<Long, List<SysDept>> collect = list.stream().collect(Collectors.groupingBy(TreeEntity::getParentId));
        List<SysDept> deptList = collect.get(100L);
        List<GradeDTO> res = BeanCopyUtils.copyList(deptList, GradeDTO.class);
        if (res == null) {
            return null;
        }
        res.forEach(e -> {
                e.setColleges(BeanCopyUtils.copyList(collect.get(e.getDeptId()), CollegeDTO.class));
                if (e.getColleges() != null) {
                    e.getColleges().forEach(m -> {
                        m.setList(BeanCopyUtils.copyList(collect.get(m.getDeptId()), ProfessionalDTO.class));
                        if (m.getList() != null) {
                            m.getList().forEach(
                                f -> f.setList(BeanCopyUtils.copyList(collect.get(f.getDeptId()), ClassDTO.class))
                            );
                        }
                    });
                }
            }
        );
        return res;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @ApiOperation("获取当前微信登录学生信息")
    public AjaxResult getInfo() {
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        WxUserDTO copy = BeanCopyUtils.copy(user, WxUserDTO.class);
        if (user.getDeptId() == null) {
            copy.setWxClassDTO(null);
            return AjaxResult.success(copy);
        }
        SysDept one = sysDeptService.getOne(Wrappers.lambdaQuery(SysDept.class)
            .eq(SysDept::getDeptId, user.getDeptId())
            .select(SysDept::getAncestors,SysDept::getDeptName)
        );
        String[] split = one.getAncestors().split(",");
        Long[] ids = new Long[split.length];
        for (int i = 0; i < split.length; i++) {
            ids[i] = Long.valueOf(split[i]);
        }
        List<String> list = sysDeptService.selectAllP(ids);
        WxClassDTO wxClassDTO = new WxClassDTO();
        wxClassDTO.setClassName(one.getDeptName());
        wxClassDTO.setAcademy(list.get(list.size() - 2));
        wxClassDTO.setSpecialty(list.get(list.size() - 1));
        wxClassDTO.setGrade(list.get(list.size() - 3));
        copy.setWxClassDTO(wxClassDTO);
        return AjaxResult.success(copy);
    }

    @ApiOperation("学生选择班级")
    @GetMapping("/studentChoosesClass")
    public AjaxResult studentChoosesClass(Long classId) {
        if (classId == null) {
            return AjaxResult.error("classId不能为空");
        }
        userService.updateClassIdByUserId(classId);
        return AjaxResult.success("操作成功");
    }

    /**
     * 修改用户信息
     *
     * @return 用户信息
     */
    @PostMapping("/updateWxUser")
    @ApiOperation("修改用户信息")
    public AjaxResult updateUser(@Validated @RequestBody WxUserVo wxUser) {
        if (wxUser == null) {
            return AjaxResult.error("参数不能为空");
        }
        SysUser user1 = userService.selectUserById(SecurityUtils.getUserId());
        if (wxUser.getUserName() != null) {
            if(user1.getUserName().equals(wxUser.getUserName())) {
                return AjaxResult.error("学号已存在");
            }
        }
        BeanCopyUtils.copyProperties(wxUser, user1);
        return toAjax(userService.updateById(user1));
    }
}
